import json
import threading

import requests
from flask import Blueprint, request, jsonify, session, abort
from flask_login import login_required, current_user

from app.iot_mqtt.iot_funciton import ai_queue
from app.models import Conversation, Message, Role, UserSettings, SystemRoles
from app import db
from datetime import datetime
from flask import request, jsonify
import os
import pandas as pd  # 用于处理CSV文件

bp = Blueprint('conversations', __name__)

queue_lock = threading.Lock()

API_KEY = "sk-rimxfijfnszhifubccdbgngodmfiqkmgkwyakivnmnpjuisr"
API_URL = "https://api.siliconflow.cn/v1/chat/completions"


@bp.route('/start_conversation', methods=['POST'])
@login_required
def start_conversation():
    data = request.get_json()
    role_id = data.get('role_id')

    if not role_id:
        return jsonify({'error': '请选择角色'}), 400

    role = Role.query.get(role_id)
    if not role:
        return jsonify({'error': '角色不存在'}), 404

    # 创建新对话
    conversation = Conversation(
        user_id=current_user.id,
        role_id=role_id,
        title=f"与 {role.name} 的对话 - {datetime.now().strftime('%Y-%m-%d')}"
    )

    db.session.add(conversation)
    db.session.commit()

    # 添加系统提示消息
    if role.system_prompt:
        system_message = Message(
            conversation_id=conversation.id,
            role='system',
            content=role.system_prompt
        )
        db.session.add(system_message)
        db.session.commit()

    return jsonify({
        'success': True,
        'conversation_id': conversation.id,
        'title': conversation.title
    })


@bp.route('/get_conversation', methods=['GET'])
@login_required
def get_conversation():
    conversation_id = request.args.get('conversation_id')
    if not conversation_id:
        return jsonify({'error': '缺少对话ID'}), 400

    conversation = Conversation.query.get(conversation_id)
    if not conversation or conversation.user_id != current_user.id:
        return jsonify({'error': '对话不存在或无权访问'}), 404

    messages = Message.query.filter_by(conversation_id=conversation.id) \
        .order_by(Message.created_at.asc()).all()

    return jsonify({
        'conversation': {
            'id': conversation.id,
            'title': conversation.title,
            'role_id': conversation.role_id,
            'created_at': conversation.created_at.isoformat(),
            'messages': [{
                'id': msg.id,
                'role': msg.role,
                'content': msg.content,
                'created_at': msg.created_at.isoformat()
            } for msg in messages]
        }
    })


def send_message_for_task(data):
    """专门用于定时任务的发送消息函数"""
    # print("this is good")
    if isinstance(data["message"], dict):
        data["message"] = json.dumps(data["message"])  # 将字典转为 JSON 字符串
    elif not isinstance(data["message"], str):
        data["message"] = str(data["message"])  # 强制转为字符串

    result, conv_or_error = sch_send_message_core(
        user_id=data["user_id"],
        message=data["message"],
        role_id=data["role_id"],
        conversation_id=data.get("conversation_id")
    )

    if result is None:
        print(f"发送消息失败: {conv_or_error}")  # conv_or_error 是错误信息
        return None
    else:
        # print(f"AI回复: {result}, 对话ID: {conv_or_error}")
        return result  # 只返回 AI 回复


# 角色系统表
def sch_send_message_core(user_id, message, role_id, conversation_id=None):
    role = SystemRoles.query.filter_by(id=role_id).first()
    if not role:
        return None, "Role not found"  # 返回 (None, error_message)

    if conversation_id:
        conversation = Conversation.query.filter_by(id=conversation_id, user_id=user_id).first()
        if not conversation:
            return None, "Conversation not found"
    else:
        conversation = Conversation(
            user_id=user_id,
            role_id=role_id,
            title=message[:20] + "..." if len(message) > 20 else message
        )
        db.session.add(conversation)
        db.session.commit()

        system_message = Message(
            conversation_id=conversation.id,
            role='system',
            content=role.system_prompt
        )
        db.session.add(system_message)
        db.session.commit()

    user_msg = Message(
        conversation_id=conversation.id,
        role='user',
        content=message
    )
    db.session.add(user_msg)
    db.session.commit()

    try:
        payload = {
            "model": "deepseek-ai/DeepSeek-V3",
            "messages": [{"role": msg.role, "content": msg.content}
                         for msg in
                         Message.query.filter_by(conversation_id=conversation.id).order_by(Message.created_at)],
            "stream": False,
            "max_tokens": UserSettings.query.get(user_id).max_tokens,
            "temperature": UserSettings.query.get(user_id).temperature,
            "top_p": UserSettings.query.get(user_id).top_p,
            "presence_penalty": UserSettings.query.get(user_id).presence_penalty,
            "frequency_penalty": UserSettings.query.get(user_id).frequency_penalty
        }

        headers = {
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        }

        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        ai_response = response.json()["choices"][0]["message"]["content"]

        ai_msg = Message(
            conversation_id=conversation.id,
            role='assistant',
            content=ai_response
        )
        print("this is good")
        print(ai_msg.content)
        db.session.add(ai_msg)
        db.session.commit()
        return ai_response, conversation.id  # 成功返回 (response, conv_id)
    except Exception as e:
        print(f"API请求失败: {str(e)}")
        return None, str(e)  # 失败返回 (None, error_message)


# 网页专用的对话代码
def _send_message_core(user_id, message, role_id, conversation_id=None):
    role = Role.query.filter_by(id=role_id, user_id=session['user_id']).first()
    if not role:
        return jsonify({"success": False, "error": "Role not found"})

    # 获取或创建对话
    if conversation_id:
        conversation = Conversation.query.filter_by(id=conversation_id, user_id=session['user_id']).first()
        if not conversation:
            return jsonify({"success": False, "error": "Conversation not found"})
    else:
        # 创建新对话
        conversation = Conversation(
            user_id=session['user_id'],
            role_id=role_id,
            title=message[:20] + "..." if len(message) > 20 else message
        )
        db.session.add(conversation)
        db.session.commit()

        # 添加系统消息
        system_message = Message(
            conversation_id=conversation.id,
            role='system',
            content=role.system_prompt
        )
        db.session.add(system_message)
        db.session.commit()

    # 添加用户消息
    user_msg = Message(
        conversation_id=conversation.id,
        role='user',
        content=message
    )
    db.session.add(user_msg)
    db.session.commit()

    # 构造API请求 (这部分保持不变)
    payload = {
        "model": "deepseek-ai/DeepSeek-V3",
        "messages": [{"role": msg.role, "content": msg.content}
                     for msg in
                     Message.query.filter_by(conversation_id=conversation.id).order_by(Message.created_at)],
        "stream": False,
        "max_tokens": UserSettings.query.get(session['user_id']).max_tokens,
        "temperature": UserSettings.query.get(session['user_id']).temperature,
        "top_p": UserSettings.query.get(session['user_id']).top_p,
        "presence_penalty": UserSettings.query.get(session['user_id']).presence_penalty,
        "frequency_penalty": UserSettings.query.get(session['user_id']).frequency_penalty
    }

    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        ai_response = response.json()["choices"][0]["message"]["content"]

        # 添加AI回复
        ai_msg = Message(
            conversation_id=conversation.id,
            role='assistant',
            content=ai_response
        )
        db.session.add(ai_msg)
        db.session.commit()
        print(ai_response)
        return ai_response, conversation.id
    except:
        print("Error occurred")


@bp.route('/send_message', methods=['POST'])
@login_required
def send_message():
    if 'user_id' not in session:
        return jsonify({"success": False, "error": "Not authenticated"})

    data = request.json
    print("data", data)
    try:
        response, conv_id = _send_message_core(
            user_id=session['user_id'],
            message=data.get('message'),
            role_id=data.get('role_id'),
            conversation_id=data.get('conversation_id')
        )
        print("good")
        return jsonify({"success": True, "response": response, "conversation_id": conv_id})
    except Exception as e:
        print("error")
        return jsonify({"success": False, "error": str(e)})


@bp.route('/send_weather', methods=['POST'])
@login_required
def send_weather():
    if 'user_id' not in session:
        return jsonify({"success": False, "error": "Not authenticated"})

    data = request.json
    print("data", data)
    try:
        response, conv_id = sch_send_message_core(
            user_id=session['user_id'],
            message=data.get('message'),
            role_id=data.get('role_id'),
            conversation_id=data.get('conversation_id')
        )
        print("good")
        return jsonify({"success": True, "response": response, "conversation_id": conv_id})
    except Exception as e:
        print("error")
        return jsonify({"success": False, "error": str(e)})


# @bp.route('/send_message', methods=['POST'])
# @login_required
# def send_message():
#     if 'user_id' not in session:
#         return jsonify({"success": False, "error": "Not authenticated"})
#
#     data = request.json
#     user_message = data.get('message', '')
#     conversation_id = data.get('conversation_id')
#     role_id = data.get('role_id')
#
#     if not user_message:
#         return jsonify({"success": False, "error": "Empty message"})
#
#     # 获取当前角色
#     role = Role.query.filter_by(id=role_id, user_id=session['user_id']).first()
#     if not role:
#         return jsonify({"success": False, "error": "Role not found"})
#
#     # 获取或创建对话
#     if conversation_id:
#         conversation = Conversation.query.filter_by(id=conversation_id, user_id=session['user_id']).first()
#         if not conversation:
#             return jsonify({"success": False, "error": "Conversation not found"})
#     else:
#         # 创建新对话
#         conversation = Conversation(
#             user_id=session['user_id'],
#             role_id=role_id,
#             title=user_message[:20] + "..." if len(user_message) > 20 else user_message
#         )
#         db.session.add(conversation)
#         db.session.commit()
#
#         # 添加系统消息
#         system_message = Message(
#             conversation_id=conversation.id,
#             role='system',
#             content=role.system_prompt
#         )
#         db.session.add(system_message)
#         db.session.commit()
#
#     # 添加用户消息
#     user_msg = Message(
#         conversation_id=conversation.id,
#         role='user',
#         content=user_message
#     )
#     db.session.add(user_msg)
#     db.session.commit()
#
#     # 构造API请求 (这部分保持不变)
#     payload = {
#         "model": "deepseek-ai/DeepSeek-V3",
#         "messages": [{"role": msg.role, "content": msg.content}
#                      for msg in
#                      Message.query.filter_by(conversation_id=conversation.id).order_by(Message.created_at)],
#         "stream": False,
#         "max_tokens": UserSettings.query.get(session['user_id']).max_tokens,
#         "temperature": UserSettings.query.get(session['user_id']).temperature,
#         "top_p": UserSettings.query.get(session['user_id']).top_p,
#         "presence_penalty": UserSettings.query.get(session['user_id']).presence_penalty,
#         "frequency_penalty": UserSettings.query.get(session['user_id']).frequency_penalty
#     }
#
#     headers = {
#         "Authorization": f"Bearer {API_KEY}",
#         "Content-Type": "application/json"
#     }
#
#     try:
#         response = requests.post(API_URL, json=payload, headers=headers)
#         response.raise_for_status()
#         ai_response = response.json()["choices"][0]["message"]["content"]
#
#         # 添加AI回复
#         ai_msg = Message(
#             conversation_id=conversation.id,
#             role='assistant',
#             content=ai_response
#         )
#         db.session.add(ai_msg)
#         db.session.commit()
#         print(ai_response)
#         return jsonify({
#             "success": True,
#             "response": ai_response,
#             "conversation_id": conversation.id
#         })
#     except Exception as e:
#         return jsonify({"success": False, "error": str(e)})


@bp.route('/get_conversations', methods=['GET'])
@login_required
def get_conversations():
    conversations = current_user.conversations.order_by(Conversation.updated_at.desc()).all()

    return jsonify({
        'conversations': [{
            'id': conv.id,
            'title': conv.title,
            'role_id': conv.role_id,
            'role_name': conv.role.name if conv.role else None,
            'updated_at': conv.updated_at.isoformat()
        } for conv in conversations]
    })


UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


@bp.route('/chat', methods=['POST'])
@login_required
def handle_chat():
    message = request.form.get('message')
    role = request.form.get('role')
    file = request.files.get('file')

    file_content = None
    if file and file.filename:
        # 保存文件
        filepath = os.path.join(UPLOAD_FOLDER, file.filename)
        file.save(filepath)

        # 根据文件类型处理内容
        if file.filename.endswith('.csv'):
            df = pd.read_csv(filepath)
            print("ccv good")
            file_content = df.to_string()
        elif file.filename.endswith('.txt'):
            print('txt good')
            with open(filepath, 'r') as f:

                file_content = f.read()
        # 可以添加其他文件类型的处理

    # 这里可以根据message、role和file_content生成回复
    reply = f"已收到您的{'消息: ' + message if message else ''}" + \
            f"{'和文件: ' + file.filename if file else ''}" + \
            f"{'，角色: ' + role if role else ''}"

    return jsonify({
        'status': 'success',
        'reply': reply,
        'file_info': {
            'name': file.filename if file else None,
            'type': file.content_type if file else None,
            'size': os.path.getsize(filepath) if file else None
        }
    })


@bp.route('/chat/history', methods=['GET'])
@login_required
def get_chat_history():
    # 从数据库获取当前用户的对话列表（不是消息）
    conversations = Conversation.query.filter_by(user_id=current_user.id).order_by(Conversation.updated_at.desc()).all()

    return jsonify([{
        'id': conv.id,
        'title': conv.title,
        'role_id': conv.role_id,
        'created_at': conv.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        'updated_at': conv.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
        'message_count': conv.messages.count()  # 获取对话中的消息数量
    } for conv in conversations])


@bp.route('/chat/history/<string:conversation_id>', methods=['GET'])
@login_required
def get_chat_conversation(conversation_id):
    # 获取特定对话及其所有消息
    conversation = Conversation.query.get_or_404(conversation_id)

    # 检查对话是否属于当前用户
    if conversation.user_id != current_user.id:
        abort(403)

    # 获取对话中的所有消息（按时间排序）
    messages = conversation.messages.order_by(Message.created_at.asc()).all()

    return jsonify({
        'id': conversation.id,
        'title': conversation.title,
        'role_id': conversation.role_id,
        'created_at': conversation.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        'updated_at': conversation.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
        'messages': [{
            'id': msg.id,
            'role': msg.role,
            'content': msg.content,
            'created_at': msg.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for msg in messages]
    })


@bp.route('/chat/history/<string:conversation_id>/messages', methods=['GET'])
@login_required
def get_conversation_messages(conversation_id):
    conversation = Conversation.query.get_or_404(conversation_id)

    if conversation.user_id != current_user.id:
        abort(403)

    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    pagination = conversation.messages.order_by(Message.created_at.asc()) \
        .paginate(page=page, per_page=per_page, error_out=False)

    messages = pagination.items

    return jsonify({
        'messages': [{
            'id': msg.id,
            'role': msg.role,
            'content': msg.content,
            'created_at': msg.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for msg in messages],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': pagination.page
    })
